Page({
  data: {
    aname: '',
    location: '',
    number: '',
    introduction: '',
    startTime: '',
    endTime: '',
    images: [],
    introLength: 0,
    multiArray: [
      [], // 年
      [], // 月
      [], // 日
      [], // 时
      [] // 分
    ],
    startMultiIndex: [0, 0, 0, 0, 0],
    endMultiIndex: [0, 0, 0, 0, 0],
    startTimeDisplay: '请选择开始时间',
    endTimeDisplay: '请选择结束时间',
  },

  onLoad: function () {
    // 初始化时间选择器数据
    this.initTimePickerArray();
  },
  initTimePickerArray() {
    const date = new Date();
    const years = [];
    const months = [];
    const days = [];
    const hours = [];
    const minutes = [];

    // 获取年份，从当前年份开始，往后推5年
    for (let i = date.getFullYear(); i <= date.getFullYear() + 5; i++) {
      years.push(i + '年');
    }

    // 获取月份
    for (let i = 1; i <= 12; i++) {
      months.push(i < 10 ? '0' + i + '月' : i + '月');
    }

    // 获取天数
    for (let i = 1; i <= 31; i++) {
      days.push(i < 10 ? '0' + i + '日' : i + '日');
    }

    // 获取小时
    for (let i = 0; i < 24; i++) {
      hours.push(i < 10 ? '0' + i + '时' : i + '时');
    }

    // 获取分钟
    for (let i = 0; i < 60; i++) {
      minutes.push(i < 10 ? '0' + i + '分' : i + '分');
    }

    // 设置当前时间索引
    const currentYear = date.getFullYear();
    const currentMonth = date.getMonth() + 1;
    const currentDay = date.getDate();
    const currentHour = date.getHours();
    const currentMinute = date.getMinutes();

    const currentIndex = [
      0, // 年份默认选中第一个（当前年）
      currentMonth - 1,
      currentDay - 1,
      currentHour,
      currentMinute
    ];

    this.setData({
      multiArray: [years, months, days, hours, minutes],
      startMultiIndex: currentIndex,
      endMultiIndex: currentIndex,
      currentDate: date
    });
  },

  // 开始时间选择器改变事件
  bindStartMultiPickerChange(e) {
    const indexArr = e.detail.value;
    const timeStr = this.formatTimeFromIndex(indexArr);

    // 检查是否早于当前时间
    if (this.isDateEarlierThanNow(timeStr)) {
      wx.showToast({
        title: '不能选择早于当前时间',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    this.setData({
      startMultiIndex: indexArr,
      startTime: timeStr,
      startTimeDisplay: timeStr
    });

    // 如果结束时间早于新的开始时间，更新结束时间
    if (this.data.endTime && this.data.endTime < timeStr) {
      this.setData({
        endTime: timeStr,
        endTimeDisplay: timeStr,
        endMultiIndex: indexArr
      });
    }
  },

  // 结束时间选择器改变事件
  bindEndMultiPickerChange(e) {
    const indexArr = e.detail.value;
    const timeStr = this.formatTimeFromIndex(indexArr);

    // 检查是否早于当前时间
    if (this.isDateEarlierThanNow(timeStr)) {
      wx.showToast({
        title: '不能选择早于当前时间',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 检查是否早于开始时间
    if (this.data.startTime && timeStr < this.data.startTime) {
      wx.showToast({
        title: '结束时间不能早于开始时间',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    this.setData({
      endMultiIndex: indexArr,
      endTime: timeStr,
      endTimeDisplay: timeStr
    });
  },

  // 检查日期是否早于当前时间
  isDateEarlierThanNow(dateStr) {
    const now = new Date();
    const selectedDate = new Date(dateStr.replace(/-/g, '/'));
    return selectedDate < now;
  },

  // 列改变事件（用于处理月份天数联动）
  bindStartMultiPickerColumnChange(e) {
    const detail = e.detail;
    const column = detail.column;
    const value = detail.value;

    if (column === 0 || column === 1) {
      const multiArray = [...this.data.multiArray];
      const multiIndex = [...this.data.startMultiIndex];

      multiIndex[column] = value;

      const year = parseInt(multiArray[0][multiIndex[0]].replace('年', ''));
      const month = parseInt(multiArray[1][multiIndex[1]].replace('月', ''));

      const daysInMonth = this.getDaysInMonth(year, month);
      const days = [];

      // 如果是当前月份，从当前日期开始
      const now = new Date();
      const startDay = (year === now.getFullYear() && month === now.getMonth() + 1) ?
        now.getDate() :
        1;

      for (let i = startDay; i <= daysInMonth; i++) {
        days.push(i < 10 ? '0' + i + '日' : i + '日');
      }

      multiArray[2] = days;

      if (multiIndex[2] >= days.length) {
        multiIndex[2] = days.length - 1;
      }

      this.setData({
        multiArray,
        startMultiIndex: multiIndex
      });
    }
  },

  bindEndMultiPickerColumnChange(e) {
    const detail = e.detail;
    const column = detail.column;
    const value = detail.value;

    if (column === 0 || column === 1) {
      const multiArray = [...this.data.multiArray];
      const multiIndex = [...this.data.endMultiIndex];

      multiIndex[column] = value;

      const year = parseInt(multiArray[0][multiIndex[0]].replace('年', ''));
      const month = parseInt(multiArray[1][multiIndex[1]].replace('月', ''));

      const daysInMonth = this.getDaysInMonth(year, month);
      const days = [];

      // 如果是当前月份，从当前日期开始
      const now = new Date();
      const startDay = (year === now.getFullYear() && month === now.getMonth() + 1) ?
        now.getDate() :
        1;

      for (let i = startDay; i <= daysInMonth; i++) {
        days.push(i < 10 ? '0' + i + '日' : i + '日');
      }

      multiArray[2] = days;

      if (multiIndex[2] >= days.length) {
        multiIndex[2] = days.length - 1;
      }

      this.setData({
        multiArray,
        endMultiIndex: multiIndex
      });
    }
  },

  // 获取指定年月的天数
  getDaysInMonth(year, month) {
    return new Date(year, month, 0).getDate();
  },


  // 格式化时间
  formatTimeFromIndex(indexArr) {
    const year = this.data.multiArray[0][indexArr[0]].replace('年', '');
    const month = this.data.multiArray[1][indexArr[1]].replace('月', '');
    const day = this.data.multiArray[2][indexArr[2]].replace('日', '');
    const hour = this.data.multiArray[3][indexArr[3]].replace('时', '');
    const minute = this.data.multiArray[4][indexArr[4]].replace('分', '');
    return `${year}-${month}-${day} ${hour}:${minute}`;
  },

  // 列改变事件（用于处理月份天数联动）
  bindStartMultiPickerColumnChange(e) {
    // 可以在这里处理月份对应的天数变化
  },

  bindEndMultiPickerColumnChange(e) {
    // 可以在这里处理月份对应的天数变化
  },



  bindStartDateChange: function (event) {
    this.setData({
      startTime: event.detail.value
    });
  },

  bindEndDateChange: function (event) {
    this.setData({
      endTime: event.detail.value
    });
  },

  handleNameInput: function (event) {
    this.setData({
      aname: event.detail.value
    });
  },

  handleLocationInput: function (event) {
    this.setData({
      location: event.detail.value
    });
  },

  handleParticipantsInput: function (event) {
    this.setData({
      number: event.detail.value
    });
  },

  handleIntroInput: function (event) {
    this.setData({
      introduction: event.detail.value,
      introLength: event.detail.value.length
    });
  },
  chooseImage: function () {
    const that = this
    wx.chooseImage({
      count: 1, // 只选择一张图片
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const app = getApp()
        const filePath = res.tempFilePaths[0]; // 取第一张图片
        wx.uploadFile({
          url: `${app.globalData.baseUrl}/upload`, // 替换为你的后端上传地址
          filePath: filePath,
          name: 'file',
          success(uploadRes) {
            try {
              const data = JSON.parse(uploadRes.data);
              console.log(data)
              that.setData({
                images: [...that.data.images, data.data] // 假设后端返回的 JSON 中有 url 字段
              });
            } catch (e) {
              console.error('解析返回数据失败:', e);
              // wx.showToast({
              //   title: '上传失败，返回数据格式错误',
              //   icon: 'none'
              // });
            }
          },
          fail(err) {
            console.error('上传失败:', err);
            // 检查是否为413错误（请求实体太大）
            if (err.statusCode === 413) {
              wx.showModal({
                title: '上传失败',
                content: '上传的图片太大了，请选择小于1MB的图片',
                showCancel: false
              });
            } else {
              wx.showToast({
                title: '上传失败，请重试',
                icon: 'none'
              });
            }
          },
          // 添加complete回调以捕获所有可能的HTTP状态码
          complete(res) {
            if (res.statusCode === 413) {
              wx.showModal({
                title: '上传失败',
                content: '上传的图片太大了，请选择小于1MB的图片',
                showCancel: false
              });
            }
          }
        });
      }
    })
  },
  previewImage: function (event) {
    const index = event.currentTarget.dataset.index; // 获取点击的图片索引
    const currentUrl = this.data.images[index]; // 获取当前图片的 URL
    wx.previewImage({
      current: currentUrl, // 当前显示图片的http链接
      urls: this.data.images // 需要预览的图片http链接列表
    });
  },

  deleteImage(e) {
    const index = e.currentTarget.dataset.index
    const images = this.data.images
    images.splice(index, 1)
    this.setData({
      images
    })
  },

  submitForm: function () {
    const {
      aname,
      startTime,
      endTime,
      location,
      number,
      introduction,
      images
    } = this.data;
    // 转换时间格式为 LocalDateTime
    const startDateTime = startTime.replace(' ', 'T') + ':00';
    const endDateTime = endTime.replace(' ', 'T') + ':00';


    // 格式化 startTime 和 endTime
    // const formattedStartTime = this.formatDateTime(startTime);
    // const formattedEndTime = this.formatDateTime(endTime);
    console.log(startTime, endTime, location, number, introduction, images)
    // 表单验证
    if (!startTime || !endTime || !location || !number || !introduction) {
      wx.showToast({
        title: '请填写所有必填项',
        icon: 'none',
        duration: 2000
      });
      return; // 终止提交
    }
    const app = getApp();
    return app.activityApi.createActvity({
      aname,
      startTime: startDateTime,
      endTime: endDateTime,
      location,
      number,
      introduction,
      images
    }).then(() => {
      // 清空输入框
      this.setData({
        aname: '',
        startTime: '', // 清空开始时间
        endTime: '', // 清空结束时间
        location: '', // 清空活动地点
        number: '', // 清空计划人数
        introduction: '', // 清空活动介绍
        images: [], // 清空图片数组
        introLength: 0 // 重置字数计数
      });
      // 正确写法（使用setTimeout保证执行顺序）
      wx.showToast({
        title: '活动发起成功',
        icon: 'success',
        duration: 2000,
        mask: true
      });

      // 延迟执行返回操作
      setTimeout(() => {
        wx.navigateBack();
      }, 2000); // 保持与duration相同的延迟时间
    });
  },
})